package com.sample.openalpr.slice;


import com.cjt2325.cameralibrary.util.LogUtil;
import com.example.openalpr_ohos.ResourceTable;
import com.sample.openalpr.CameraAbility;
import com.sample.openalpr.LocalPicturceAbility;
import com.squareup.picasso.Picasso;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.DataAbilityHelper;
import ohos.aafwk.ability.DataAbilityRemoteException;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.*;
import ohos.agp.render.Canvas;
import ohos.agp.render.Paint;
import ohos.agp.render.Texture;
import ohos.agp.utils.Color;
import ohos.agp.utils.Rect;
import ohos.agp.window.dialog.ToastDialog;
import ohos.app.Context;
import ohos.app.Environment;
import ohos.bundle.IBundleManager;
import ohos.global.icu.text.SimpleDateFormat;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.utils.net.Uri;

import java.io.File;
import java.io.FileDescriptor;
import java.io.FileNotFoundException;
import java.nio.file.OpenOption;
import java.util.*;


public class MainAbilitySlice extends AbilitySlice {
    private static final int SLICE_CODE = 0;
    private final int REQUEST_IMAGE = 100;
    private final int REQUEST_FILE = 42;
    private final int STORAGE = 1;

    private String ANDROID_DATA_DIR;
    private File imgFolder;
    private File imageFile;

    private Context appCtx;
    private Image imageView;
    private TextField txtCountry;
    private TextField txtRegion;
    private TextField txtCandidatesNum;
    private TableLayout resultTable;

    private static final HiLogLabel LABEL = new HiLogLabel(HiLog.LOG_APP, 0x00201, "qqqqqq");

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
    /*    Image demo= (Image) findComponentById(ResourceTable.Id_demo);
        demo.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
            //present(new camerademo.slice.MainAbilitySlice(),new Intent());
                Intent intent = new Intent();
                Operation operation =
                        new Intent.OperationBuilder()
                                .withBundleName(getBundleName())
                                .withAbilityName(CameraAbility.class.getName())
                                .build();
                intent.setOperation(operation);
                startAbility(intent);
              // PermissionBridge.getHandler().sendEvent(EVENT_PERMISSION_GRANTED);
            }
        });*/
        checkPermission();
        appCtx = this;
        ANDROID_DATA_DIR = this.getApplicationInfo().getEntryDir();
        txtCandidatesNum = (TextField) findComponentById(ResourceTable.Id_txtCandidatesNum);
        txtCountry = (TextField) findComponentById(ResourceTable.Id_txtCountry);
        txtRegion = (TextField) findComponentById(ResourceTable.Id_txtRegion);

        resultTable = (TableLayout) findComponentById(ResourceTable.Id_resultTable);
        imageView = (Image) findComponentById(ResourceTable.Id_imageView);

        findComponentById(ResourceTable.Id_btnTakePicture).setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                takePicture();
            }
        });

        findComponentById(ResourceTable.Id_btnLoad).setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                loadPicture();
            }
        });

        findComponentById(ResourceTable.Id_btnClear).setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                resultTable.setVisibility(Component.HIDE);
                int count = resultTable.getChildCount();
                for (int i = 1; i < count; i++) {
                    Component child = resultTable.getComponentAt(i);
                    //     if (child instanceof TableRow) ((ComponentContainer) child).removeAllComponents();
                }
                new ToastDialog(appCtx).setText("Result table cleared!").setDuration(1).show();
            }
        });

        findComponentById(ResourceTable.Id_btnFlushDir).setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                int cont = 0;
                for (File file : imgFolder.listFiles()) {
                    if (file.delete()) ++cont;
                }
                new ToastDialog(appCtx).setText(cont + " files deleted successfully!").setDuration(1).show();
            }
        });

        imgFolder = new File(Environment.DIRECTORY_DOCUMENTS + "/OpenALPR/");
        if (!imgFolder.exists()) {
            imgFolder.mkdir();
        }
    }

    /*   @Override
       protected void onAbilityResult(int requestCode, int resultCode, Intent resultData) {
           super.onAbilityResult(requestCode, resultCode, resultData);
           if ((requestCode == REQUEST_IMAGE || requestCode == REQUEST_FILE) && resultCode == -1) {
               final long startTime = System.currentTimeMillis();
               final long[] endTime = new long[1];
               //-------------------------------------------
             //  final ProgressDialog progress = ProgressDialog.show(this, "Loading", "Parsing result...", true);
               final String openAlprConfFile = ANDROID_DATA_DIR + File.separatorChar + "runtime_data" + File.separatorChar + "openalpr.conf";

             *//*  BitmapFactory.Options options = new BitmapFactory.Options();
            options.inSampleSize = 10;*//*

            if (requestCode == REQUEST_FILE) {
                if (resultData != null && resultData.getUri() != null) {
                   // String path = Environment.getExternalStorageDirectory().getPath() + "/" + resultData.getData().getLastPathSegment().split(":")[1];
                   Uri uri= resultData.getUri();

                    imageFile = new File(uri.getDecodedPath());
                    Picasso.get().invalidate(imageFile);
                }
            }

            final int[] x1 = { 0 };
            final int[] x2 = { 0 };
            final int[] y1 = { 0 };
            final int[] y2 = { 0 };
            final String[] plate = {""};
            new Thread()
            {
                @Override
                public void run() {
                    int candidates = txtCandidatesNum.getText().toString().isEmpty()? 5 : Integer.parseInt((txtCandidatesNum.getText().toString()));
                    String result = OpenALPR.Factory.create(appCtx, ANDROID_DATA_DIR).recognizeWithCountryRegionNConfig(txtCountry.getText().toString(), txtRegion.getText().toString(), imageFile.getAbsolutePath(), openAlprConfFile, candidates);
                    try {
                    //    final Results results = new Gson().fromJson(result, Results.class);
                  *//*      getContext().getUITaskDispatcher().asyncDispatch(new Runnable() {
                            @Override
                            public void run() {
                                resultTable.setVisibility(Component.VISIBLE);
                                if (results == null || results.getResults() == null || results.getResults().size() == 0) {
                                    new ToastDialog(getContext()).setText("It was not possible to detect the licence plate.").setDuration(1).show();
                                } else {
                                    endTime[0] = System.currentTimeMillis();
                                    TableLayout.LayoutParams rowLayoutParams = new TableLayout.LayoutParams(TableLayout.LayoutParams.FILL_PARENT, TableLayout.LayoutParams.WRAP_CONTENT);
                                    TableRow.LayoutParams cellLayoutParams = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT);

                                    List<Result> resultsList = results.getResults();
                                    for(int i = 0; i < resultsList.size(); ++i) {
                                        Result result = resultsList.get(i);

                                        if (i == 0) { // save rectangle coordinates and plate of best result
                                            x1[0] = result.getCoordinates().get(0).getX();
                                            y1[0] = result.getCoordinates().get(0).getY();
                                            x2[0] = result.getCoordinates().get(2).getX();
                                            y2[0] = result.getCoordinates().get(2).getY();
                                            plate[0] = result.getPlate();
                                        }

                                        TableRow tableRow = new TableRow(appCtx);
                                        tableRow.setLayoutParams(rowLayoutParams);

                                        if (result.getConfidence() < 60)
                                            tableRow.setBackgroundColor(Color.RED);
                                        else if (result.getConfidence() < 85)
                                            tableRow.setBackgroundColor(Color.YELLOW);
                                        else if (result.getConfidence() >= 85)
                                            tableRow.setBackgroundColor(Color.GREEN);

                                        Text cellValue = new Text(appCtx);
                                        cellValue.setTypeface(null, Typeface.BOLD);
                                        cellValue.setText(result.getPlate());
                                        cellValue.setLayoutParams(cellLayoutParams);
                                        tableRow.addView(cellValue);

                                        cellValue = new Text(appCtx);
                                        cellValue.setTypeface(null, Typeface.BOLD);
                                        cellValue.setText(String.format("%.2f", result.getConfidence())+"%");
                                        cellValue.setLayoutParams(cellLayoutParams);
                                        tableRow.addView(cellValue);

                                        String region = txtCountry.getText().toString()+"_"+txtRegion.getText().toString();
                                        cellValue = new Text(appCtx);
                                        cellValue.setTypeface(null, Typeface.BOLD);
                                        cellValue.setText(region.length() == 1? "n/a" : region);
                                        cellValue.setLayoutParams(cellLayoutParams);
                                        tableRow.addView(cellValue);

                                        cellValue = new Text(appCtx);
                                        cellValue.setTypeface(null, Typeface.BOLD);
                                        cellValue.setText(String.format("%.2f", result.getMatchesTemplate()));
                                        cellValue.setLayoutParams(cellLayoutParams);
                                        tableRow.addView(cellValue);

                                        cellValue = new Text(appCtx);
                                        cellValue.setTypeface(null, Typeface.BOLD);
                                        cellValue.setText(String.format("%.2f", ((result.getProcessingTimeMs() / 1000.0) % 60)) + " s");
                                        cellValue.setLayoutParams(cellLayoutParams);
                                        tableRow.addView(cellValue);

                                        resultTable.addView(tableRow);
                                        List<Candidate> candidates = result.getCandidates();
                                        for (int j = 1; j < candidates.size(); ++j) {
                                            Candidate candidate = candidates.get(j);
                                            tableRow = new TableRow(appCtx);
                                            tableRow.setLayoutParams(rowLayoutParams);
                                            tableRow.setBackgroundColor(Color.LTGRAY);

                                            cellValue = new Text(appCtx);
                                            cellValue.setText(candidate.getPlate());
                                            cellValue.setLayoutParams(cellLayoutParams);
                                            tableRow.addView(cellValue, 0);

                                            cellValue = new Text(appCtx);
                                            cellValue.setText(String.format("%.2f", candidate.getConfidence())+"%");
                                            cellValue.setLayoutParams(cellLayoutParams);
                                            tableRow.addView(cellValue, 1);

                                            tableRow.addView(new Text(appCtx), 2);

                                            cellValue = new Text(appCtx);
                                            cellValue.setText(String.valueOf(candidate.getMatchesTemplate()));
                                            cellValue.setLayoutParams(cellLayoutParams);
                                            tableRow.addView(cellValue, 3);
                                            resultTable.addView(tableRow);
                                        }
                                    }
                                    resultTable.invalidate();
                                    new ToastDialog(appCtx).setText("Processing time: "+ String.format("%.2f", (((endTime[0]-startTime) / 1000.0) % 60)) + " s").setDuration(1).show();
                                }
                            }
                        });*//*


                    } catch (Exception exception) {
                      *//*  final ResultsError resultsError = new Gson().fromJson(result, ResultsError.class);
                        getContext().getUITaskDispatcher().asyncDispatch(new Runnable() {
                            @Override
                            public void run() {
                                new ToastDialog(appCtx).setText(resultsError.getMsg()).setDuration(1).show();
                            }
                        });*//*

                    }
//-------------------
                  //  progress.dismiss();
                    getContext().getUITaskDispatcher().asyncDispatch(new Runnable() {
                        @Override
                        public void run() {
                            // Picasso requires permission.WRITE_EXTERNAL_STORAGE
//                            Picasso.with(MainAbilitySlice.this).load(imageFile).fit().centerCrop().into(imageView);
                            Picasso.get().load(imageFile).fit().centerCrop().into(imageView);
                            if (imageView.getImageElement() != null) {
//                                PixelMap bitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
                                PixelMap bitmap = ((PixelMap) imageView.getPixelMap());

                              //  PixelMap originalBitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath(), new BitmapFactory.Options());
                                ImageSource imageSource = ImageSource.create(imageFile.getAbsoluteFile(), null);
                                PixelMap originalBitmap =imageSource.createPixelmap(null);
                                float viewWidth = bitmap.getImageInfo().size.width;
                                float viewHeigth = bitmap.getImageInfo().size.height;
                                float originalWidth = originalBitmap.getImageInfo().size.width;
                                float originalHeigth = originalBitmap.getImageInfo().size.height;

                              //  Canvas canvas = new Canvas(bitmap);
                                Texture texture=new Texture(bitmap);
                                Canvas canvas=new Canvas(texture);
                                //Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
                                Paint paint = new Paint();
                                paint.setColor(Color.GREEN);
                                paint.setStyle(Paint.Style.STROKE_STYLE);
                                paint.setStrokeWidth(8);

                                // map rectangle coordinates to imageview
                                int p1_x = (int)((x1[0] * viewWidth) / originalWidth);
                                int p1_y = (int)((y1[0] * viewHeigth) / originalHeigth);
                                int p2_x = (int)((x2[0] * viewWidth) / originalWidth);
                                int p2_y = (int)((y2[0] * viewHeigth) / originalHeigth);
                                canvas.drawRect(new Rect(p1_x, p1_y, p2_x, p2_y), paint);

                                paint.setTextSize(75);
                                paint.setStyle(Paint.Style.FILL_STYLE);
                             //   paint.setTypeface(Typeface.DEFAULT_BOLD);
                                paint.setColor(Color.YELLOW);
                                canvas.drawText(paint,plate[0], p1_x, p1_y-10);
//                                imageView.setImageBitmap(bitmap);
                                imageView.setPixelMap(bitmap);
                            }
                        }
                    });

                }
            }.start();


        }
    }
*/
    private void checkPermission() {
        List<String> permissions = new ArrayList<>();
        if (verifySelfPermission("ohos.permission.WRITE_MEDIA") != IBundleManager.PERMISSION_GRANTED) {
            permissions.add("ohos.permission.WRITE_MEDIA");
        }

        if (!permissions.isEmpty()) {
            new ToastDialog(getContext()).setText("Storage access needed to manage the picture.").setDuration(1).show();
            String[] params = permissions.toArray(new String[permissions.size()]);
            requestPermissionsFromUser(params, STORAGE);
            //ActivityCompat.requestPermissions(this, params, STORAGE);
        }
    }

    @Override
    public void requestPermissionsFromUser(String[] permissions, int requestCode) {
//        super.requestPermissionsFromUser(permissions, requestCode);
        switch (requestCode) {
            case STORAGE: {
                Map<String, Integer> perms = new HashMap<>();
                // Initial
//                perms.put(Manifest.permission.WRITE_EXTERNAL_STORAGE, IBundleManager.PERMISSION_GRANTED);
                perms.put("android.permission.WRITE_EXTERNAL_STORAGE", IBundleManager.PERMISSION_GRANTED);
                // Fill with results
                for (int i = 0; i < permissions.length; i++)
//                    perms.put(permissions[i], grantResults[i]);
                    perms.put(permissions[i], requestCode);
                // Check for WRITE_EXTERNAL_STORAGE
//                Boolean storage = perms.get(Manifest.permission.WRITE_EXTERNAL_STORAGE) == IBundleManager.PERMISSION_GRANTED;
                Boolean storage = perms.get("android.permission.WRITE_EXTERNAL_STORAGE") == IBundleManager.PERMISSION_GRANTED;
                if (storage) {
                    // permission was granted, yay!
                } else {
                    // Permission Denied
                    new ToastDialog(getContext()).setText("Storage permission is needed to analyse the picture.").setDuration(1).show();
                }
            }
            default:
                break;
        }
    }


    public String dateToString(Date date, String format) {
        SimpleDateFormat df = new SimpleDateFormat(format, Locale.getDefault());

        return df.format(date);
    }

    /*    public void takePicture() {
            // Generate the path for the next photo
            String name = dateToString(new Date(), "yyyy-MM-dd-hh-mm-ss");
            imageFile = new File(imgFolder, name + ".jpg");

    //        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            Intent intent = new Intent();
            Operation builder= new Intent.OperationBuilder().withAction("android.media.action.IMAGE_CAPTURE").build();
            intent.setOperation(builder);
    //        intent.setParam("MediaStore.EXTRA_OUTPUT", Uri.getUriFromFile(imageFile));
            intent.setParam(" output", Uri.getUriFromFile(imageFile));
            startAbility(intent, REQUEST_IMAGE);
        }*/
    public void takePicture() {
     //   presentForResult(new CameraSlice(), new Intent(), SLICE_CODE);
        Intent intent = new Intent();
        Operation openOption = new Intent.OperationBuilder()
                .withBundleName(getBundleName())
                .withAbilityName(CameraAbility.class.getName())
                .build();
        intent.setOperation(openOption);
        startAbilityForResult(intent,SLICE_CODE);
    }

    public void loadPicture() {
/*        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("image/*");
        startAbilityForResult(intent, REQUEST_FILE);*/
        //-----------
    /*    Intent intent=new Intent();
        Operation builder= new Intent.OperationBuilder().withAction("android.intent.action.OPEN_DOCUMENT").build();
        intent.setOperation(builder);
        intent.addEntity("android.intent.category.OPENABLE");
        intent.setType("image/*");
        startAbilityForResult(intent, REQUEST_FILE);*/
      //  present(new LocalPictureChoose(), new Intent());
        Intent intent = new Intent();
        Operation openOption = new Intent.OperationBuilder()
                .withBundleName(getBundleName())
                .withAbilityName(LocalPicturceAbility.class.getName())
                .build();
        intent.setOperation(openOption);
startAbilityForResult(intent,REQUEST_IMAGE);
    }


    @Override
    public void onActive() {
        super.onActive();
        if (imageFile != null) {// Picasso does not seem to have an issue with a null value, but to be safe
            // Picasso.with(MainAbilitySlice.this).load(imageFile).fit().centerCrop().into(imageView);
            Picasso.get().load(imageFile).fit().centerCrop().into(imageView);
        }
    }

    @Override
    protected void onResult(int requestCode, Intent resultIntent) {
        super.onResult(requestCode, resultIntent);
        try {
            if (requestCode == SLICE_CODE && resultIntent != null) {
                if (resultIntent.hasParameter("PHOTO_URL")) {
                    String photoUrl = resultIntent.getStringParam("PHOTO_URL");
                    if (photoUrl == null || "".equals(photoUrl)) {
                        return;
                    }
                    PixelMap pixelMa = ImageSource.create(photoUrl, null).createPixelmap(null);
                    imageView.setPixelMap(pixelMa);
                    LogUtil.info(LogUtil.DEFAULT_TAG, "onResult photoUrl:" + photoUrl);
                    HiLog.error(LABEL, "************************");
                    HiLog.error(LABEL, "photoUrl: " + photoUrl);
                    HiLog.error(LABEL, "pixelMa: " + pixelMa);
                    HiLog.error(LABEL, "************************");
                }
            }
        } catch (Exception vrp) {
            LogUtil.info(LogUtil.DEFAULT_TAG, "onResult error:" + vrp.getMessage());
        }
    }

    @Override
    protected void onAbilityResult(int requestCode, int resultCode, Intent resultData) {
        super.onAbilityResult(requestCode, resultCode, resultData);
        try {
            if (requestCode == SLICE_CODE && resultData != null) {
                if (resultData.hasParameter("PHOTO_URL")) {
                    String photoUrl = resultData.getStringParam("PHOTO_URL");
                    if (photoUrl == null || "".equals(photoUrl)) {
                        return;
                    }
                    PixelMap pixelMa = ImageSource.create(photoUrl, null).createPixelmap(null);
                    imageView.setPixelMap(pixelMa);
                    LogUtil.info(LogUtil.DEFAULT_TAG, "onResult photoUrl:" + photoUrl);
                    HiLog.error(LABEL, "************************");
                    HiLog.error(LABEL, "photoUrl: " + photoUrl);
                    HiLog.error(LABEL, "pixelMa: " + pixelMa);
                    HiLog.error(LABEL, "************************");
                    return;
                }
            }
        } catch (Exception vrp) {
            LogUtil.info(LogUtil.DEFAULT_TAG, "onResult error:" + vrp.getMessage());
        }
        if (requestCode==REQUEST_IMAGE&&resultData!=null)
        {
            DataAbilityHelper helper = DataAbilityHelper.creator(this);
            FileDescriptor fd = null;
            try {
                fd = helper.openFile(resultData.getUri(), "r");
                ImageSource.DecodingOptions decodingOptions = new ImageSource.DecodingOptions();
                ImageSource  imageSource = ImageSource.create(fd, null);
                PixelMap pixelMap = imageSource.createPixelmap(null);
                imageView.setPixelMap(pixelMap);
            } catch (DataAbilityRemoteException e) {
                e.printStackTrace();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }

        }
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
}
